package com.example.xyxwebbackend001.controller;

import com.example.xyxwebbackend001.common.CommonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @PostMapping("/{model}")
    public CommonResult<Object> handleFileUpload(
            @PathVariable String model,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "userId", required = false) Integer userId) {

        try {
            if (file.isEmpty()) {
                return CommonResult.fail(400, "上传文件不能为空");
            }

            String uploadDir = "D:/ResourceRepository";
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path path = Paths.get(uploadDir + fileName);

            Files.createDirectories(path.getParent());
            file.transferTo(path);

            return CommonResult.message("文件上传成功: " + fileName);

        } catch (IOException e) {
            return CommonResult.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("系统异常: " + e.getMessage());
        }
    }
}
